package com.burgess.net;

import com.burgess.net.dao.ArticleDao;
import com.burgess.net.dao.AuthorDao;
import com.burgess.net.model.Article;
import com.burgess.net.model.Author;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Mybatis单独使用测试类
 */
public class MyBatisTest2 {

    private SqlSessionFactory sqlSessionFactory;

    /**
     * 加载配置文件，并创建sqlSessionFactory
     * @throws IOException
     */
    @Before
    public void prepare() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        inputStream.close();
    }

    /**
     * 用于从数据库中查询某篇文章和相应的作者信息
     */
    @Test
    public void testOne2One() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            ArticleDao articleDao = session.getMapper(ArticleDao.class);
            Article article = articleDao.findOne(1);

            Author author = article.getAuthor();
            article.setAuthor(null);

            System.out.println("\nauthor info:");
            System.out.println(author);
            System.out.println("\narticles info:");
            System.out.println(article);
        } finally {
            session.close();
        }
    }

    /**
     * 用于查询某位作者，及其所写的文章的信息
     */
    @Test
    public void testOne2Many() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            AuthorDao authorDao = session.getMapper(AuthorDao.class);
            Author author = authorDao.findOne(1);

            List<Article> arts = author.getArticles();
            List<Article> articles = Arrays.asList(arts.toArray(new Article[arts.size()]));
            arts.clear();

            System.out.println("\nauthor info:");
            System.out.println(author);
            System.out.println("\narticles info:");
            articles.forEach(System.out::println);
        } finally {
            session.close();
        }
    }

}
